from fastapi import HTTPException, status
from fastapi.responses import JSONResponse


class AuthException(HTTPException):
    def __init__(
            self,
            status_code: int = status.HTTP_401_UNAUTHORIZED,
            detail: str = None,
            code: int = 40101,
            msg: str = "认证失败"
    ):
        self.code = code
        self.msg = msg
        super().__init__(
            status_code=status_code,
            detail=detail,
            headers={"WWW-Authenticate": "Bearer"}  # 保持OAuth2规范
        )

    def to_response(self):
        """直接将异常转换为JSON响应"""
        return JSONResponse(
            status_code=self.status_code,
            content={
                "code": self.code,
                "msg": self.msg,
                "detail": self.detail,
                "data": None
            }
        )